#!/usr/bin/python
'''
/*
 * This computer program is the confidential information and proprietary trade
 * secret of VistaraIT LLC.  Possessions and use of this program must  conform
 * strictly to the license agreement between the user and VistaraIT LLC.,  and
 * receipt or possession does not convey any rights to divulge, reproduce,  or
 * allow others to use this program without specific written authorization  of
 * VistaraIT LLC.
 * 
 * Copyright (c) 2014 VistaraIT, Inc. All rights reserved.
 */
'''

from django.shortcuts import render_to_response
from webutils import SessionUtils,WebUtils
from appliance.appliancemanager import ApplianceManager
from appliance.configmanager import ConfigManager

def index(request):
    username = request.POST['username']
    password = request.POST['password']
    manager = ApplianceManager()
    try:
        configmanager = ConfigManager()
        appliance_title = configmanager.getProperty(configmanager.APPLIANCE_TITLE)
    except:
        appliance_title = "Vistara Gateway"
    if manager.authenticateAdmin(username, password):
        SessionUtils(request).setAttribute('flag','True')
        return render_to_response('common/redirect.html',{'uri':'/'})
    errors = ['Incorrect username or password']
    return render_to_response('login.html',{"errors":errors,"appliance_title":appliance_title})

def loginPage(request):
    errorcode = 0
    errors = []
    try:
        configmanager = ConfigManager()
        appliance_title = configmanager.getProperty(configmanager.APPLIANCE_TITLE)
    except:
        appliance_title = "Service Gateway"
    try:
        errorcode = request.GET.get('errorno')
    except:
        pass
    if errorcode == '1':
        errors = ["An Active User has overridden your session."]
    return render_to_response('login.html',{"errors":errors,"appliance_title":appliance_title})

def logout(request,errorCode=0):
    try:
        del request.session['flag']
    except KeyError:
        pass
    try:
        if WebUtils().isActiveSession(request.session.session_key):
            WebUtils().destroyActiveSession()
    except:
        pass
    uri = '/login'
    if errorCode > 0 :
        uri = uri + "?errorno=" + str(errorCode)
    return render_to_response('common/redirect.html',{'uri':uri})
